import { Injectable } from '@angular/core';
import { SetofkeyService } from "../service/setofkey.service";
import { SetofvalueService } from "../service/setofvalue.service";
import { Http } from "@angular/http";
import { SetofkeyDict, SetofvalueDict, ValueDict } from "../entity/setof-dict.model";
import { Setofvalue } from "../entity/setofvalue.model";
import { Subject } from "rxjs/Rx";
import "rxjs/add/observable/of";
import "rxjs/add/operator/do";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class SetofDictService {


  /**
   * 数据字典
   * 例如：
   * constructor(private setofDictService:SetofDictService){
   *    let tagSets:Setofvalue[]= setofDictService.getSetofValues["AudioParameter"]
   *    let tagSet:Setofvalue= setofDictService.getSetofValue["TagSet"]["01"]
   * }
   * 
   * 
   * 
   * @static
   * @type {SetofKeyDict}
   * @memberof SetofDict
   */
  public getSetofValues: SetofkeyDict = {};

  /**
   * 数据字典
   * 例如：
   * setofDict.setofValue["TagSet"]["01"] => Setofvalue
   * 
   * 
   * @static
   * @type {SetofKeyDict}
   * @memberof SetofDict
   */
  public getSetofValue: SetofvalueDict = {};


  private keyService: SetofkeyService;
  private valueService: SetofvalueService;

  constructor(private http: InterceptorService) {
   
  }


  /**
   * 添加[@]避免以数字字符开头出现错误
   * 
   * @private
   * @memberof SetofDict
   */
  public initData(): Promise<boolean> {
    this.keyService = new SetofkeyService(this.http);
    this.valueService = new SetofvalueService(this.http);
    let keys = this.keyService.getSetofkeys();
    let values = this.valueService.getSetofValues();
    return Promise.all([keys, values])
      .then(res => {
        res[0].forEach(setofkey => {
          let keyValues = res[1].filter(o => o.keyId === setofkey.keyId);
          if (keyValues != null && keyValues.length > 0) {
            //对key数组复制
            this.getSetofValues[setofkey.keyCode] = keyValues;
            try {
              //初始化对象
              let setOfValueDict: ValueDict = {};
              keyValues.forEach(keyValue => {
                setOfValueDict[keyValue.valueCode] = keyValue;
              });
              //对Value数组赋值
              this.getSetofValue[setofkey.keyCode] = setOfValueDict;

              return Promise.resolve(true);
            }
            catch (error) {              
              throw new Error(error)
            }
          }
        });

      })
      .catch(this.handleError);
  
  }




  private handleError(error: any): Promise<any> {

    return Promise.reject(error.message || error);
  }
}



// WEBPACK FOOTER //
// ./src/app/service/setof-dict.service.ts